package com.facade;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dao.MembershipDAO;
import com.model.Membership;
import com.objects.MembershipSearch;

public class MembershipFacade implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private MembershipDAO membershipDAO = new MembershipDAO();

	public void createMembership(Membership membership) {
		membershipDAO.beginTransaction();
		membershipDAO.save(membership);
		membershipDAO.commitAndCloseTransaction();
	}
	
	public Membership findMemberWithName(String name) {
		membershipDAO.beginTransaction();
		Membership membership = membershipDAO.findMemberWithName(name);
		membershipDAO.closeTransaction();
		return membership;
	}
	
	public Membership findMemberWithId(int id) {
		membershipDAO.beginTransaction();
		Membership membership = membershipDAO.findMemberWithId(id);
		membershipDAO.closeTransaction();
		return membership;
	}	
	
	public List<Membership> listAll() {
		membershipDAO.beginTransaction();
		List<Membership> result = membershipDAO.findAll();
		membershipDAO.closeTransaction();

		return result;
	}	
	
	public List<Membership> listActive() {
		membershipDAO.beginTransaction();
		List<Membership> result = membershipDAO.listActive();
		membershipDAO.closeTransaction();
		
		return result;
	}		
	
	public void updateMembership(Membership membership) {
		membershipDAO.beginTransaction();
		Membership persistedMembership = membershipDAO.find(membership.getId());
		persistedMembership.setName(membership.getName());
		persistedMembership.setDescription(membership.getDescription());
		persistedMembership.setPrice(membership.getPrice());
		persistedMembership.setMonthValidity(membership.getMonthValidity());
		persistedMembership.setEffectiveFrom(membership.getEffectiveFrom());
		persistedMembership.setEffectiveTo(membership.getEffectiveTo());
		persistedMembership.setSessionValidity(membership.getSessionValidity());
		persistedMembership.setActive(membership.isActive());
		persistedMembership.setRenewable(membership.isRenewable());
		persistedMembership.setUpdatedBy(membership.getUpdatedBy());
		persistedMembership.setUpdatedDate(membership.getUpdatedDate());
		membershipDAO.commitAndCloseTransaction();
	}	
	
	public List<Membership> search(MembershipSearch membershipSearch){
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("name", "%"+membershipSearch.getName()+"%");
		parameters.put("active", membershipSearch.isActive());
		parameters.put("priceFrom", membershipSearch.getPriceFrom());
		parameters.put("priceTo", membershipSearch.getPriceTo());
		
		membershipDAO.beginTransaction();
		List<Membership> resultList = membershipDAO.search(parameters);
		membershipDAO.closeTransaction();
		
		return resultList;
	}	
	

}
